path = require('path');

module.exports = function(grunt) {

	grunt.initConfig
    ({
        pkg : grunt.file.readJSON('package.json'),
        meta : {
            banner : '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= pkg.author %> - '
                    + '<%= grunt.template.today("yyyy-mm-dd HH:MM:ss") %> */'
        },
        releaseDate:String(new Date().getTime()),
        concat : {
            releaseDateCss: {
                src : 'dist/styles/main.css',
                dest : 'dist/styles/main_<%=releaseDate%>.css'
            },
            library : {
                src : [ 
                        'libs/jquery-1.10.2.js',             //jquery
                        'libs/handlebars-1.1.2.js',    		//handlbars
                        'libs/crypto/ccrypto.js',
                        'libs/crypto/crypto-sha1.js',
                        'libs/crypto/e2e.js',
                        'libs/spin.min.js',                 //loding indicator
                        'libs/jquery.dateFormat-1.0.js',    //date
                        'libs/ember-1.2.0.js',
                        'libs/require.js',
                        'libs/moment_min.js',               //date
                        'libs/moment_en-gb.js',             //date
                        'libs/ember-animated-outlet.min.js',
                        'libs/jSignature.min.noconflict.js',	//canvas sign
                        'libs/iscroll.js',
                        'libs/amplify.min.js',               // topic, request, store
						'libs/bootstrap-datepicker.js'               // datepicker
                ],
                dest : 'dist/libs.js'
            }
        },
        aggregate : {
            default:{
                groups: {
                    main: {
                        src: [
                            'common/app.js',
                            'common/router.js',
                            'common/modules/**/*.js'
                        ]
                    },
                    core: {
                        src: [
                            'common/core/**/*.js'
                        ]
                    }
                },
                destdir : 'dist/',
                srcdir : 'app/'
            },
            wrapper : {
                groups: {
                    main: {
                        src: [
                            'common/**/*.js'
                        ]
                    },
                    core: {
                        src: [
                            'common/core/**/*.js'
                        ]
                    }
                },
                destdir : 'dist/',
                srcdir : 'app/'
            }
        },
        uglify: {
            dist:{
                files:{
                    'dist/main_<%=releaseDate%>.js': 'dist/main_<%=releaseDate%>.js',
                    'dist/core_<%=releaseDate%>.js': 'dist/core_<%=releaseDate%>.js'
                }
            },
            wrapper_dist:{
                files:{
                    'dist/main_<%=releaseDate%>.js': 'dist/main_<%=releaseDate%>.js',
                    'dist/core_<%=releaseDate%>.js': 'dist/core_<%=releaseDate%>.js'
                }
            },
            library:{
                files: {
                    '<%=concat.library.dest%>':'<%=concat.library.dest%>'
                }
            },
            template:{
                files: {
                    'dist/templates_main_<%=releaseDate%>.js':'dist/templates_main_<%=releaseDate%>.js'
                }
            },
            wrapper_template:{
                files: {
                    'dist/templates_main_<%=releaseDate%>.js':'dist/templates_main_<%=releaseDate%>.js'
                }
            }
        },
        copy: {
            all:{
                files: [
                    {
                        expand: true,     // Enable dynamic expansion.
                        cwd: 'app/css/',// Src matches are relative to this path.
                        src: ['**/*'], // Actual pattern(s) to match.
                        dest: 'dist/css/'  // Destination path prefix.
                    },					
                    {
                        expand: true,     // Enable dynamic expansion.
                        cwd: 'app/js/',// Src matches are relative to this path.
                        src: ['**/*'], // Actual pattern(s) to match.
                        dest: 'dist/js/'  // Destination path prefix.
                    },					
                    {
                        expand: true,     // Enable dynamic expansion.
                        cwd: 'app/images/',// Src matches are relative to this path.
                        src: ['**/*'], // Actual pattern(s) to match.
                        dest: 'dist/images/'  // Destination path prefix.
                    },					
                    {
                        expand: true,     // Enable dynamic expansion.
                        cwd: 'app/',      // Src matches are relative to this path.
                        src: ['**/index.html'], // Actual pattern(s) to match.
                        dest: 'dist/'  // Destination path prefix.
                    },
                    {
                        expand: true,     // Enable dynamic expansion.
                        cwd: 'app/fonts/',// Src matches are relative to this path.
                        src: ['**'], // Actual pattern(s) to match.
                        dest: 'dist/fonts/'  // Destination path prefix.
                    },
                    {
                        expand: true,     // Enable dynamic expansion.
                        cwd: 'app/cordova/',// Src matches are relative to this path.
                        src: ['**'], // Actual pattern(s) to match.
                        dest: 'dist/cordova/'  // Destination path prefix.
                    }
                ]
            }
        },
        clean :{
            build: {
                src: ["dist/"],
                options: { force: true }
            }
        },
        watch : {
            files : [ 'app/**/*'],
            tasks : [ 'on-watch' ]
        },
        jshint : {
            options : {
                curly : true,
                eqeqeq : true,
                immed : true,
                latedef : true,
                newcap : true,
                noarg : true,
                sub : true,
                undef : true,
                boss : true,
                eqnull : true,
                es5 : true
            },
            all : [ 'app/common/**/*.js' ]
        },
        server : {
            appName : 'breeze'
        },
        compass : {
            all: {
                config: 'config.rb'
            }
        },
        compress : {
        	main: {
                options: {
                    archive: 'release/breeze.zip'
                },
                files: [
                	{
                        expand: true,	// Enable dynamic expansion.
                        cwd: 'dist/',	// Src matches are relative to this path.
                        src: ['**/*'], 	// Actual pattern(s) to match.
                        dest: '/'		// Destination path prefix.
                    }
                ]
            }
        },
        ember_templates : {
            compile : {
                options : {
                    templateName : function(sourceFile) {
                        return sourceFile.substring(sourceFile
                            .lastIndexOf('/') + 1,
                            sourceFile.length);
                    }
                },
                files : {
                    'dist/templates_main_<%=releaseDate%>.js' : [
                        'app/common/modules/*.hbs',
                        'app/common/modules/**/*.hbs'
                    ]           
                }
            },
            wrapper: {
                options : {
                    templateName : function(sourceFile) {
                        return sourceFile.substring(sourceFile
                            .lastIndexOf('/') + 1,
                            sourceFile.length);
                    }
                },
                files : {
                    'dist/templates_main_<%=releaseDate%>.js' : [
                        'app/common/modules/*.hbs',
                        'app/common/modules/**/*.hbs'
                    ]
                }
            }
        },
        replace : {
            country : {
                options : {
                    variables : {
                        'projectName' : 'sg',
                        'cssName' : 'main_<%=releaseDate%>'
                    },
                    prefix : '@@'
                },
                files : {
                    'dist/index.html' : [ 'dist/index.html' ]
                }
            },
            sit : {
                options : {
                    variables : {
                        'version' : '<%=releaseDate%>'
                    },
                    prefix : '@@'
                },
                files : {
                	'dist/main_<%=releaseDate%>.js' : [ 'dist/main_<%=releaseDate%>.js' ],
                	'dist/index.html' : [ 'dist/index.html' ]
                }
            },
            oat : {
                options : {
                    variables : {
                        'version' : '<%=releaseDate%>'
                    },
                    prefix : '@@'
                },
                files : {
                	'dist/main_<%=releaseDate%>.js' : [ 'dist/main_<%=releaseDate%>.js' ],
                	'dist/index.html' : [ 'dist/index.html' ]
                }
            },
            wrapper_uat : {
                options : {
                    variables : {
                        'version' : '<%=releaseDate%>'
                    },
                    prefix : '@@'
                },
                files : {
                    'dist/main_<%=releaseDate%>.js' : [ 'dist/main_<%=releaseDate%>.js' ],
                    'dist/index.html' : [ 'dist/index.html' ]
                }
            },
            wrapper : { //prod
                options : {
                    variables : {
                        'version' : '<%=releaseDate%>'
                    },
                    prefix : '@@'
                },
                files : {
                	'dist/main_<%=releaseDate%>.js' : [ 'dist/main_<%=releaseDate%>.js' ],
                	'dist/index.html' : [ 'dist/index.html' ]
                }
            }
        },
		jsdoc : {
			dist : {
				src: ['dist/core_<%=releaseDate%>.js'], 
				options: {
					destination: 'doc',
					template: "node_modules/ink-docstrap/template"
				}
			}
		}
    });

	// Default task.
	grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-compass');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-compress');
	grunt.loadNpmTasks('grunt-ember-handlebars');
	grunt.loadNpmTasks('grunt-ember-templates');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-replace');
    grunt.loadNpmTasks('grunt-data-uri');
    grunt.loadNpmTasks('grunt-contrib-imagemin');
    grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-jsdoc');

    grunt.registerTask('refineLcov', 'refine lcov report for sonar-javascript-plugin', function() {
        var absPath = require('path').resolve('./');
        var lcovData = grunt.file.read('test/junit/coverage/lcov/lcov.info');
        var lines = lcovData.split('\n');
        var refinedData = [];
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].indexOf('DA:') === 0 || lines[i].indexOf('end_of_record') === 0) {
                refinedData.push(lines[i]);
            } else if (lines[i].indexOf('SF:./') === 0) {
                refinedData.push(lines[i].replace('SF:./', 'SF:' + absPath + '/'));
            }
        }
        grunt.file.write('test/junit/jsTestDriver.conf-coverage.dat', refinedData.join('\n'));
    });

    grunt
        .registerTask(
        'server',
        'Start a custom web server.',
        function() {
            this.async();
            var t_args = [].slice.call(arguments);
            var t_country = t_args[0], t_env = t_args[1], t_src = t_args[2],t_locate = t_args[3], t_appName = grunt
                .config("server")['appName'], t_serverConfigs = require('./server/server-config.js');

            var t_hostInfo = t_serverConfigs['country'][t_country][t_env],
                t_locate_hostInfo = t_serverConfigs['country'][t_country][t_env][t_locate],
                t_srcPath = t_serverConfigs['src'][t_src];
            var t_config = {
                host : t_hostInfo,
                locate:t_locate_hostInfo,
                src : t_srcPath,
                appName : t_appName,
                country : t_country
            };
            require('./server/server.js').run(t_config);

            grunt.log.writeln('Server is starting....');

        });

    grunt
        .registerTask(
        'aggregate',
        'Aggregate files of specific country and concat them as given orders.',
        function(countryCode, arg) {
            var config = null;
            if(arg !== undefined)
                config = grunt.config('aggregate')[arg];
            else
                config = grunt.config('aggregate')['default'];
            var target = null,
                separator = config.separator ? config.separator : '\n',
                srcdir = config.srcdir ? config.srcdir : '',
                destdir = config.destdir ? config.destdir : '',
                releaseDate = grunt.config('releaseDate');

            for (var groupName in config.groups) {
                var group = config.groups[groupName];
                var dest = destdir + '/' + groupName + '_'+releaseDate+'.js';
                var fileList = [];

                for (target in group.src) {
                    fileList = fileList.concat(group.src[target]);
                    fileList.push(group.src[target].replace(
                        'common', 'country/' + countryCode));
                }

                var files = fileList.map(function(filepath) {
                    return filepath.indexOf('<') == -1 ? srcdir + '/'
                        + filepath : filepath;
                });

                files = grunt.file.expand({
                    filter: function(src){
                        if (group.exclude) {
                            return group.exclude.indexOf(path.basename(src)) === -1;
                        }
                        return true;
                    }
                }, files);
                files = grunt.file.expand(files);

                // Concat specified files.
                var helpers = require('grunt-lib-legacyhelpers').init(grunt);
                // then, replace any call to helpers:

                // with this:
                var srcData =  helpers.concat(files, {
                    separator : separator
                });

                grunt.file.write(dest, srcData);

                // Fail task if errors were logged.
                if (this.errorCount) {
                    return false;
                }

                // Otherwise, print a success message.
                grunt.log
                    .writeln('File "' + dest + '" created.');
            }
        });

    // common tasks used across the different profile
    grunt.registerTask('common', ['clean']);
    grunt.registerTask('specific', ['common', 'aggregate:sg', 'ember_templates:compile', 'concat', 'copy:all', 'compass', 'concat:releaseDateCss', 'replace:country', "jsdoc"]);


    grunt.registerTask('on-watch', [
        'specific',
        'replace:sit',
        // 'server:sg:sit:release:locate'
    ]);

    grunt.registerTask('run-sit', [
        'specific',
        'replace:sit',
        'server:sg:sit:release:locate'
    ]);

    grunt.registerTask('run-mock', [
        'specific',
        'replace:sit',
        'server:sg:mock:release:locate'
    ]);

    grunt.registerTask('package', [
        'specific',
        'uglify:template',
        'uglify:dist',
        'uglify:library',
        'replace:sit',
        'compress'
    ]);

    grunt.registerTask('package-oat', [
        'specific',
        'uglify:template',
        'uglify:dist',
        'uglify:library',
        'replace:oat',
        'compress'
    ]);

    grunt.registerTask('wrapper-build', [
        'common',
        'aggregate:sg:wrapper',
        'ember_templates:wrapper',
        'concat',
        'copy:all',
        'compass',
        'concat:releaseDateCss',
        'replace:country'
    ]);

    grunt.registerTask('wrapper-package', [ //prod
        'wrapper-build',
        'replace:wrapper'
    ]);

    grunt.registerTask('wrapper-package-uat', [ //uat
        'wrapper-build',
        'replace:wrapper_uat'
    ]);

	// grunt.registerTask('watch');
};
